document.addEventListener('DOMContentLoaded', function () {
  // 获取所有表单和切换按钮
  const loginForm = document.getElementById('loginForm');
  const registerForm = document.getElementById('registerForm');
  const forgotForm = document.getElementById('forgotForm');
  const adminLoginForm = document.getElementById('adminLoginForm');
  const pendingApprovalForm = document.getElementById('pendingApprovalForm');
  const securityQuestionsForm = document.createElement('div');
  securityQuestionsForm.className = 'form-box';
  securityQuestionsForm.id = 'securityQuestionsForm';

  document.querySelector('.form-container').appendChild(securityQuestionsForm);

  const registerBtn = document.getElementById('registerBtn');
  const loginBtn = document.getElementById('loginBtn');
  const forgotBtn = document.getElementById('forgotBtn');
  const backToLoginBtn = document.getElementById('backToLoginBtn');
  const adminLoginLink = document.getElementById('adminLoginLink');
  const backToLoginFromAdmin = document.getElementById('backToLoginFromAdmin');
  const backToLoginFromPending = document.getElementById('backToLoginFromPending');

  // 当前用户状态
  let currentUser = null;
  let securityQuestions = [];
  let userSecurityQuestions = [];
  let resetUserId = null;

  // 获取角色选择和条件显示字段
  const roleSelect = document.getElementById('regRole');
  const studentFields = document.getElementById('studentFields');
  const teacherFields = document.getElementById('teacherFields');

  // 初始化时禁用所有条件性字段的required属性
  const studentInputs = document.querySelectorAll('#studentFields input, #studentFields select');
  const teacherInputs = document.querySelectorAll('#teacherFields input, #teacherFields select');

  // 默认禁用所有条件字段的必填属性
  studentInputs.forEach(input => input.required = false);
  teacherInputs.forEach(input => input.required = false);

  // 根据选择的角色显示相应的字段
  roleSelect.addEventListener('change', function () {
    const selectedRole = this.value;

    // 获取所有学生字段和教师字段的输入元素
    const studentInputs = studentFields.querySelectorAll('input, select');
    const teacherInputs = teacherFields.querySelectorAll('input, select');

    // 默认禁用所有字段的必填属性
    studentInputs.forEach(input => input.required = false);
    teacherInputs.forEach(input => input.required = false);

    if (selectedRole === 'student') {
      // 显示学生字段，隐藏教师字段
      studentFields.classList.add('active');
      teacherFields.classList.remove('active');

      // 启用学生字段的必填属性
      studentInputs.forEach(input => input.required = true);
    } else if (selectedRole === 'teacher') {
      // 显示教师字段，隐藏学生字段
      teacherFields.classList.add('active');
      studentFields.classList.remove('active');

      // 启用教师字段的必填属性
      teacherInputs.forEach(input => input.required = true);
    } else {
      // 都不显示
      studentFields.classList.remove('active');
      teacherFields.classList.remove('active');
    }
  });

  // 密保问题列表
  const securityQuestionsList = [
    '您的出生城市是?',
    '您的第一所学校名称是?',
    '您的第一个宠物名字是?',
    '您母亲的姓名是?',
    '您父亲的姓名是?',
    '您最喜欢的电影是?',
    '您的童年好友名字是?',
    '您的第一辆车的品牌是?'
  ];

  // 渲染一组密保问题
  function renderSecurityQuestions() {
    const container = document.getElementById('securityQuestionsContainer');
    container.innerHTML = '';
    const div = document.createElement('div');
    div.className = 'security-question-item';
    div.innerHTML = `
      <div class="input-group select-group">
        <select class="regSecurityQuestion" required>
          <option value="">--请选择密保问题--</option>
          ${securityQuestionsList.map(q => `<option value="${q}">${q}</option>`).join('')}
        </select>
      </div>
      <div class="input-group">
        <input type="text" class="regSecurityAnswer" required placeholder="请输入密保答案">
      </div>
    `;
    container.appendChild(div);
  }

  // 显示登录表单
  function showLoginForm() {
    loginForm.style.display = 'block';
    registerForm.style.display = 'none';
    forgotForm.style.display = 'none';
    securityQuestionsForm.style.display = 'none';
    adminLoginForm.style.display = 'none';
    pendingApprovalForm.style.display = 'none';
  }

  // 显示注册表单
  function showRegisterForm() {
    loginForm.style.display = 'none';
    registerForm.style.display = 'block';
    forgotForm.style.display = 'none';
    securityQuestionsForm.style.display = 'none';
    adminLoginForm.style.display = 'none';
    pendingApprovalForm.style.display = 'none';
  }

  // 显示忘记密码表单
  function showForgotForm() {
    loginForm.style.display = 'none';
    registerForm.style.display = 'none';
    forgotForm.style.display = 'block';
    securityQuestionsForm.style.display = 'none';
    adminLoginForm.style.display = 'none';
    pendingApprovalForm.style.display = 'none';
  }

  // 显示密保问题表单
  function showSecurityQuestionsForm() {
    loginForm.style.display = 'none';
    registerForm.style.display = 'none';
    forgotForm.style.display = 'none';
    securityQuestionsForm.style.display = 'block';
    adminLoginForm.style.display = 'none';
    pendingApprovalForm.style.display = 'none';

    renderSecurityQuestions();
  }

  // 显示管理员登录表单
  function showAdminLoginForm() {
    loginForm.style.display = 'none';
    registerForm.style.display = 'none';
    forgotForm.style.display = 'none';
    securityQuestionsForm.style.display = 'none';
    adminLoginForm.style.display = 'block';
    pendingApprovalForm.style.display = 'none';
  }

  // 显示待审核提示表单
  function showPendingApprovalForm() {
    loginForm.style.display = 'none';
    registerForm.style.display = 'none';
    forgotForm.style.display = 'none';
    securityQuestionsForm.style.display = 'none';
    adminLoginForm.style.display = 'none';
    pendingApprovalForm.style.display = 'block';
  }

  // 切换到注册表单
  registerBtn.addEventListener('click', function (e) {
    e.preventDefault();
    showRegisterForm();
  });

  // 切换到登录表单
  loginBtn.addEventListener('click', function (e) {
    e.preventDefault();
    showLoginForm();
  });

  // 切换到忘记密码表单
  forgotBtn.addEventListener('click', function (e) {
    e.preventDefault();
    showForgotForm();
  });

  // 从忘记密码返回登录
  backToLoginBtn.addEventListener('click', function (e) {
    e.preventDefault();
    showLoginForm();
  });

  // 切换到管理员登录
  adminLoginLink.addEventListener('click', function (e) {
    e.preventDefault();
    showAdminLoginForm();
  });

  // 从管理员登录返回普通登录
  backToLoginFromAdmin.addEventListener('click', function (e) {
    e.preventDefault();
    showLoginForm();
  });

  // 从待审核返回登录
  backToLoginFromPending.addEventListener('click', function (e) {
    e.preventDefault();
    showLoginForm();
  });

  // 显示提示信息
  function showAlert(message, type, elementId) {
    const messageBox = document.getElementById(elementId);
    if (messageBox) {
      messageBox.textContent = message;
      messageBox.className = 'message-box';

      if (type) {
        messageBox.classList.add(type);
      }
    } else {
      alert(message);
    }
  }

  // 登录表单处理
  loginForm.addEventListener('submit', async function (e) {
    e.preventDefault();
    const username = document.getElementById('loginUsername').value;
    const password = document.getElementById('loginPassword').value;

    if (!username || !password) {
      showAlert('请填写用户名和密码', 'error', 'loginMessage');
      return;
    }

    showAlert('正在登录...', 'info', 'loginMessage');

    try {
      const response = await fetch('/api/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password })
      });

      const data = await response.json();

      if (data.success) {
        localStorage.setItem('userToken', data.token);
        localStorage.setItem('userData', JSON.stringify(data.user));

        showAlert('登录成功，正在跳转...', 'success', 'loginMessage');

        // 根据用户角色跳转到不同页面
        if (data.user.role === 'admin') {
          window.location.href = 'admin.html';
        } else if (data.user.role === 'teacher' && data.user.status === 'approved') {
          window.location.href = 'teacher.html';
        } else if (data.user.role === 'student' && data.user.status === 'approved') {
          window.location.href = 'student.html';
        } else {
          showAlert('您的账户正在审核中，请等待管理员审核', 'info', 'loginMessage');
        }
      } else {
        showAlert(data.message || '登录失败', 'error', 'loginMessage');
      }
    } catch (error) {
      console.error('登录错误:', error);
      showAlert('网络错误，请稍后重试', 'error', 'loginMessage');
    }
  });

  // 管理员登录处理
  adminLoginForm.querySelector('form').addEventListener('submit', async function (e) {
    e.preventDefault();
    const username = document.getElementById('adminUsername').value;
    const password = document.getElementById('adminPassword').value;

    if (!username || !password) {
      showAlert('请填写管理员账号和密码', 'error', 'adminLoginMessage');
      return;
    }

    console.log('尝试管理员登录:', { username, password });
    showAlert('正在登录...', 'info', 'adminLoginMessage');

    try {
      const response = await fetch('/api/admin-login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password })
      });

      console.log('管理员登录响应状态:', response.status);

      const data = await response.json();
      console.log('管理员登录响应数据:', data);

      if (data.success) {
        localStorage.setItem('adminToken', data.token);
        showAlert('登录成功，正在跳转...', 'success', 'adminLoginMessage');
        window.location.href = 'admin.html';
      } else {
        showAlert(data.message || '管理员登录失败', 'error', 'adminLoginMessage');
      }
    } catch (error) {
      console.error('管理员登录错误:', error);
      showAlert('网络错误，请稍后重试', 'error', 'adminLoginMessage');
    }
  });

  // 注册表单提交处理
  registerForm.querySelector('form').addEventListener('submit', async function (e) {
    e.preventDefault();

    // 进行角色相关字段验证前，禁用不相关字段的required属性
    const role = document.getElementById('regRole').value;
    const studentInputs = document.querySelectorAll('#studentFields input, #studentFields select');
    const teacherInputs = document.querySelectorAll('#teacherFields input, #teacherFields select');

    if (role === 'student') {
      // 禁用教师字段的required属性
      teacherInputs.forEach(input => input.required = false);
    } else if (role === 'teacher') {
      // 禁用学生字段的required属性
      studentInputs.forEach(input => input.required = false);
    }

    const username = document.getElementById('regUsername').value;
    const email = document.getElementById('regEmail').value;
    const password = document.getElementById('regPassword').value;
    const confirmPassword = document.getElementById('regConfirmPassword').value;

    // 验证必填项
    if (!username || !email || !password || !confirmPassword || !role) {
      showAlert('请填写所有必填字段', 'error', 'registerMessage');
      return;
    }

    if (password !== confirmPassword) {
      showAlert('两次输入的密码不一致', 'error', 'registerMessage');
      return;
    }

    // 简单的邮箱格式验证
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      showAlert('请输入有效的电子邮箱地址', 'error', 'registerMessage');
      return;
    }

    // 收集用户详细信息
    let userProfile = {};

    if (role === 'student') {
      const realName = document.getElementById('regRealName').value;
      const studentId = document.getElementById('regStudentId').value;
      const department = document.getElementById('regDepartment').value;
      const className = document.getElementById('regClass').value;

      if (!realName || !studentId || !department || !className) {
        showAlert('请填写所有学生信息字段', 'error', 'registerMessage');
        return;
      }

      userProfile = {
        real_name: realName,
        student_id: studentId,
        department: department,
        class_name: className
      };
    } else if (role === 'teacher') {
      const teacherName = document.getElementById('regTeacherName').value;
      const contactNumber = document.getElementById('regContactNumber').value;

      if (!teacherName || !contactNumber) {
        showAlert('请填写所有教师信息字段', 'error', 'registerMessage');
        return;
      }

      userProfile = {
        real_name: teacherName,
        department: null,
        contact_number: contactNumber
      };
    }

    // 校验一组密保问题和答案
    const questionSelect = document.querySelector('#securityQuestionsContainer .regSecurityQuestion');
    const answerInput = document.querySelector('#securityQuestionsContainer .regSecurityAnswer');
    const q = questionSelect.value;
    const a = answerInput.value.trim();
    if (!q || !a) {
      showAlert('请填写密保问题和答案', 'error', 'registerMessage');
      e.preventDefault();
      return false;
    }
    const securityQuestion = { question: q, answer: a };

    try {
      // 添加调试输出
      console.log('准备发送注册请求，数据:', {
        username,
        email,
        password: '******', // 出于安全考虑不输出密码
        role,
        profile: userProfile,
        securityQuestion
      });

      showAlert('正在注册...', 'info', 'registerMessage');

      const response = await fetch('/api/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          username,
          email,
          password,
          role,
          profile: userProfile,
          securityQuestion
        })
      });

      console.log('注册请求状态码:', response.status);

      const data = await response.json();
      console.log('注册请求响应:', data);

      if (data.success) {
        currentUser = data.user;
        showAlert('注册成功，请等待管理员审核', 'success', 'registerMessage');
        showPendingApprovalForm();
      } else {
        showAlert(data.message || '注册失败', 'error', 'registerMessage');
      }
    } catch (error) {
      console.error('注册错误:', error);
      showAlert('网络错误，请稍后重试', 'error', 'registerMessage');
    }
  });

  // 忘记密码表单处理 - 获取密保问题
  forgotForm.querySelector('form').addEventListener('submit', async function (e) {
    e.preventDefault();
    const email = document.getElementById('forgotEmail').value;

    if (!email) {
      showAlert('请输入您的注册邮箱', 'error', 'forgotMessage');
      return;
    }

    // 简单的邮箱格式验证
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      showAlert('请输入有效的电子邮箱地址', 'error', 'forgotMessage');
      return;
    }

    try {
      const response = await fetch('/api/forgot-password', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ email })
      });

      const data = await response.json();

      if (data.success) {
        resetUserId = data.userId;
        userSecurityQuestions = data.questions;

        // 修改忘记密码表单，显示密保问题
        forgotForm.innerHTML = `
          <h2>验证密保问题</h2>
          <form id="verifySecurityForm">
            <div id="verifySecurityContainer"></div>
            <div id="forgotMessage" class="message-box"></div>
            <button type="submit">验证</button>
          </form>
          <div class="switch-form">
            <a href="#" id="backToForgotBtn">返回</a>
          </div>
        `;

        const container = document.getElementById('verifySecurityContainer');

        userSecurityQuestions.forEach(q => {
          const div = document.createElement('div');
          div.className = 'input-group';
          div.dataset.questionId = q.id;

          const questionText = document.createElement('p');
          questionText.className = 'security-question-text';
          questionText.textContent = q.question;

          const input = document.createElement('input');
          input.type = 'text';
          input.required = true;

          const label = document.createElement('label');
          label.textContent = '您的答案';

          div.appendChild(questionText);
          div.appendChild(input);
          div.appendChild(label);

          container.appendChild(div);
        });

        // 返回忘记密码表单
        document.getElementById('backToForgotBtn').addEventListener('click', function (e) {
          e.preventDefault();
          showForgotForm();
        });

        // 验证密保问题提交
        document.getElementById('verifySecurityForm').addEventListener('submit', async function (e) {
          e.preventDefault();

          const answers = [];
          userSecurityQuestions.forEach(q => {
            const div = document.querySelector(`.input-group[data-question-id="${q.id}"]`);
            const answer = div.querySelector('input[type="text"]').value.trim();

            answers.push({
              questionId: q.id,
              answer: answer
            });
          });

          try {
            const response = await fetch('/api/verify-security-answers', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify({
                userId: resetUserId,
                answers: answers
              })
            });

            const data = await response.json();

            if (data.success) {
              // 显示重置密码表单
              forgotForm.innerHTML = `
                <h2>重置密码</h2>
                <form id="resetPasswordForm">
                  <div class="input-group">
                    <input type="password" id="newPassword" required>
                    <label for="newPassword">新密码</label>
                  </div>
                  <div class="input-group">
                    <input type="password" id="confirmNewPassword" required>
                    <label for="confirmNewPassword">确认新密码</label>
                  </div>
                  <div id="forgotMessage" class="message-box"></div>
                  <button type="submit">重置密码</button>
                </form>
                <div class="switch-form">
                  <a href="#" id="backToLoginFromReset">返回登录</a>
                </div>
              `;

              // 返回登录表单
              document.getElementById('backToLoginFromReset').addEventListener('click', function (e) {
                e.preventDefault();
                showLoginForm();
              });

              // 重置密码表单提交
              document.getElementById('resetPasswordForm').addEventListener('submit', async function (e) {
                e.preventDefault();

                const newPassword = document.getElementById('newPassword').value;
                const confirmNewPassword = document.getElementById('confirmNewPassword').value;

                if (!newPassword || !confirmNewPassword) {
                  showAlert('请填写所有字段', 'error', 'forgotMessage');
                  return;
                }

                if (newPassword !== confirmNewPassword) {
                  showAlert('两次输入的密码不一致', 'error', 'forgotMessage');
                  return;
                }

                try {
                  const response = await fetch('/api/reset-password', {
                    method: 'POST',
                    headers: {
                      'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                      userId: resetUserId,
                      newPassword: newPassword,
                      token: data.resetToken
                    })
                  });

                  const resetData = await response.json();

                  if (resetData.success) {
                    showAlert('密码重置成功，请重新登录', 'success', 'forgotMessage');
                    setTimeout(() => {
                      showLoginForm();
                    }, 2000);
                  } else {
                    showAlert(resetData.message || '密码重置失败', 'error', 'forgotMessage');
                  }
                } catch (error) {
                  console.error('重置密码错误:', error);
                  showAlert('网络错误，请稍后重试', 'error', 'forgotMessage');
                }
              });
            } else {
              showAlert(data.message || '密保问题验证失败', 'error', 'forgotMessage');
            }
          } catch (error) {
            console.error('验证密保问题错误:', error);
            showAlert('网络错误，请稍后重试', 'error', 'forgotMessage');
          }
        });
      } else {
        showAlert(data.message || '邮箱未找到', 'error', 'forgotMessage');
      }
    } catch (error) {
      console.error('忘记密码错误:', error);
      showAlert('网络错误，请稍后重试', 'error', 'forgotMessage');
    }
  });

  // 初始化
  renderSecurityQuestions();
}); 